<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="试卷名称" prop="paperName">
                      <el-input
                          v-model="queryParams.paperName"
                          placeholder="试卷名称"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="题目内容" prop="content">
                      <el-input
                          v-model="queryParams.content"
                          placeholder="题目内容"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            
            type="success"
            @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
            
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
                    <el-table-column
                        key="id"
                        label="主键"
                        prop="id"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="addtime"
                        label="创建时间"
                        prop="addtime"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="paperId"
                        label="所属试卷ID"
                        prop="paperId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="paperName"
                        label="试卷名称"
                        prop="paperName"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="type"
                        label="试题类型"
                        prop="type"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="content"
                        label="题目内容"
                        prop="content"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="options"
                        label="选项(JSON格式存储)"
                        prop="options"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="answer"
                        label="题目答案"
                        prop="answer"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="analysis"
                        label="答案解析"
                        prop="analysis"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="score"
                        label="得分"
                        prop="score"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="level"
                        label="难度等级(1-5)"
                        prop="level"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="sequence"
                        label="题目顺序"
                        prop="sequence"
                        min-width="150"
                        align="center"
                    />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
                
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
                
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 试题管理表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
    
                <el-form-item label="所属试卷" prop="paperId">
                    <el-select
                        v-model="formData.paperId"
                        placeholder="请选择试卷"
                        filterable
                        clearable
                        @change="handlePaperChange"
                    >
                        <el-option
                            v-for="item in paperOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                
                
				
				<el-form-item label="试题类型">
					<dict v-model="formData.type" code="STLX" />
					<el-link underline="never" type="primary" class="ml-5">
					</el-link>
				</el-form-item>
				
				
				

                <el-form-item label="题目内容" prop="content">
                      <el-input
                          v-model="formData.content"
                          placeholder="题目内容"
                      />
                </el-form-item>
				
				
				<!-- 选择题 -->
				      <template v-if="formData.type === '1'">
				        <el-form-item
				          v-for="(option, index) in options"
				          :key="index"
				          :label="`选项 ${String.fromCharCode(65 + index)}`"
				        >
				          <el-input
				            v-model="option.text"
				            placeholder="请输入选项内容"
				            class="option-input"
							
				          >
				            <template #append>
				              
				              <el-button
				                type="danger"
				                icon="Delete"
				                circle
				                @click="removeOption(index)"
				              />
				            </template>
				          </el-input>
				        </el-form-item>
				        <el-form-item>
				          <el-button type="primary" @click="addOption">添加选项</el-button>
				        </el-form-item>
				      </template>
					  
					  

                <el-form-item label="题目答案" prop="answer">
                      <el-input
                          v-model="formData.answer"
                          placeholder="题目答案"
                      />
                </el-form-item>

                <el-form-item label="答案解析" prop="analysis">
                      <el-input
                          v-model="formData.analysis"
                          placeholder="答案解析"
                      />
                </el-form-item>

                <el-form-item label="得分" prop="score">
                      <el-input
                          v-model="formData.score"
                          placeholder="得分"
                      />
                </el-form-item>

                <el-form-item label="难度等级(1-5)" prop="level">
                      <el-input
                          v-model="formData.level"
                          placeholder="难度等级(1-5)"
                      />
                </el-form-item>

                <el-form-item label="题目顺序" prop="sequence">
                      <el-input
                          v-model="formData.sequence"
                          placeholder="题目顺序"
                      />
                </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  defineOptions({
    name: "ExamQuestion",
    inheritAttrs: false,
  });

  import ExamQuestionAPI, { ExamQuestionPageVO, ExamQuestionForm, ExamQuestionPageQuery } from "@/api/system/exam-question";

  const queryFormRef = ref();
  const dataFormRef = ref();

  const loading = ref(false);
  const removeIds = ref<number[]>([]);
  const total = ref(0);
  
  const paperOptions=ref([])
  const options=ref([])

  const queryParams = reactive<ExamQuestionPageQuery>({
    pageNum: 1,
    pageSize: 10,
  });

  // 试题管理表格数据
  const pageData = ref<ExamQuestionPageVO[]>([]);

  // 弹窗
  const dialog = reactive({
    title: "",
    visible: false,
  });

  // 试题管理表单数据
  const formData = reactive<ExamQuestionForm>({});
  

  // 试题管理表单校验规则
  const rules = reactive({
                      id: [{ required: true, message: "请输入主键", trigger: "blur" }],
                      addtime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
                      paperId: [{ required: true, message: "请输入所属试卷ID", trigger: "blur" }],
                      type: [{ required: true, message: "请输入试题类型", trigger: "blur" }],
                      content: [{ required: true, message: "请输入题目内容", trigger: "blur" }],
                      answer: [{ required: true, message: "请输入题目答案", trigger: "blur" }],
                      score: [{ required: true, message: "请输入得分", trigger: "blur" }],
  });

  /** 查询试题管理 */
  function handleQuery() {
    loading.value = true;
          ExamQuestionAPI.getPage(queryParams)
        .then((data) => {
          pageData.value = data.list;
          total.value = data.total;
        })
        .finally(() => {
          loading.value = false;
        });
  }


function QueryPaper() {
          ExamQuestionAPI.queryPaper()
        .then((data) => {
          console.log(data)
		  
		  paperOptions.value=data;
        })
       
  }
  
  
  function handlePaperChange(){
	  console.log(item);
  }
  
  // 添加选项
  function addOption (){
    options.value.push({
      text: '',
      isCorrect: false
    })
  }
  
  // 删除选项
  const removeOption = (index) => {
    if (options.value.length > 2) {
      options.value.splice(index, 1)
    } else {
      ElMessage.warning('至少需要两个选项')
    }
  }


  
  /** 重置试题管理查询 */
  function handleResetQuery() {
    queryFormRef.value!.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
  }

  /** 行复选框选中记录选中ID集合 */
  function handleSelectionChange(selection: any) {
    removeIds.value = selection.map((item: any) => item.id);
  }

  /** 打开试题管理弹窗 */
  function handleOpenDialog(id?: number) {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改试题管理";
            ExamQuestionAPI.getFormData(id).then((data) => {
        Object.assign(formData, data);
      });
    } else {
      dialog.title = "新增试题管理";
    }
  }

  /** 提交试题管理表单 */
  function handleSubmit() {
    dataFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        const id = formData.id;
        if (id) {
                ExamQuestionAPI.update(id, formData)
              .then(() => {
                ElMessage.success("修改成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        } else {
			
			let arr=[];
			
			
			for(let s in options.value){

				let label=String.fromCharCode(65 + Number(s))
				let text=options.value[s].text;
				let obj={"label":label,
				"text":text};
				arr.push(obj);
				
				
				// console.log(label+"##"+text)
			}
			formData.options=JSON.stringify(arr);
		
                ExamQuestionAPI.add(formData)
              .then(() => {
                ElMessage.success("新增成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        }
      }
    });
  }

  /** 关闭试题管理弹窗 */
  function handleCloseDialog() {
    dialog.visible = false;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
    formData.id = undefined;
  }

  /** 删除试题管理 */
  function handleDelete(id?: number) {
    const ids = [id || removeIds.value].join(",");
    if (!ids) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
        () => {
          loading.value = true;
                ExamQuestionAPI.deleteByIds(ids)
              .then(() => {
                ElMessage.success("删除成功");
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        },
        () => {
          ElMessage.info("已取消删除");
        }
    );
  }

  onMounted(() => {
    handleQuery();
	QueryPaper();
  });
</script>
